package com.example.ui_demo_widget;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends AppCompatActivity {


    private int Progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar);
        ProgressBar pb3 = findViewById(R.id.pb_3);
        Button btnAdd = findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int current = pb3.getProgress();
                int max = pb3.getMax();
                if (current < max) {
                    pb3.setProgress(current + 10);
                } else {
                    btnAdd.setEnabled(false);
                }
            }
        });

        ProgressBar pb4 = findViewById(R.id.pb_4);

        Handler handler = new Handler(Looper.getMainLooper(),new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    pb4.setProgress(Progress);
                } else {
                    Toast.makeText(ProgressBarActivity.this,
                            "加载完成",
                            Toast.LENGTH_SHORT).show();
                    pb4.setVisibility(View.GONE);
                }
                return true;
            }
        });


        new Thread(new Runnable() {
        @Override
        public void run () {
            while (true) {
                Progress += Math.random() + 10;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = new Message();
                if (Progress <= 100) {
                    msg.what = 1;
                    handler.sendMessage(msg);
                } else {
                    msg.what = -1;
                    handler.sendMessage(msg);
                    break;
                }
            }


        }
    }).

    start();

}}
